<!DOCTYPE html>
<html lang="zh-CN" xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
<head>
  <meta charset="utf-8"/>
  <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0,user-scalable=no,minimal-ui"/>
  <!-- 上述3个meta标签必须放在最前面，任何其他内容都必须跟随其后 -->
  <title>Mojito</title>
  <script src="js/base.js"></script>
  <link rel="stylesheet" href="plugins/vant/vant.min.css"/>
  <link rel="stylesheet" href="styles/common.css"/>
  <link rel="stylesheet" href="styles/index.css"/>
</head>
<body>
  <div id="main" class="app">
    <div class="divHead">
      <img src="images/user.png" alt="" @click="toUserPage"/>
    </div>
    <div class="divTitle">
      <div class="divStatic">
        <img src="images/logo.png" class="logo" alt=""/>
        <div class="divDesc">
          <div class="divName">Mojito</div>
          <div class="divSend">
            <span><img src="images/location.png" alt=""/> 距离1km</span>
            <span><img src="images/money.png" alt=""/> 配送费3元</span>
            <span><img src="images/time.png" alt=""/> 配送约30分钟</span>
          </div>
        </div>
      </div>
      <div class="divDesc">
        简介：你爱我，我爱你！Mojito甜蜜蜜！
      </div>
    </div>
    <div class="divBody">
      <div class="divType">
        <ul>
          <li v-for="(item,index) in categoryList" :key="index" :class="{active:activeIndex===index}"
              @click="changeCategory(index,item.id,item.type)">{{item.name}}</li>
        </ul>
      </div>
      <div class="divMenu">
        <div>
          <div class="divItem" v-for="(item,index) in commodityList" :key="index" @click="openDetailsDialog(item)">
            <van-image :src="getImage(item.image)">
              <template v-slot:error></template>
            </van-image>
            <div>
              <div class="divName">{{item.name}}</div>
              <div class="divDesc">{{item.description}}</div>
              <div class="divDesc">销量{{item.sales}}</div>
              <div class="divBottom"><span>￥</span><span>{{item.price}}</span></div>
              <div class="divOpera">
                <div class="divTypes" v-if="item.configs.length>0" @click.prevent.stop="openConfigDialog(item)">选规格</div>
                <div class="divAdd" v-else>
                  <img src="images/add.png" @click.prevent.stop="addCart(item,true)"/>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div :class="{divCart:true,divCartEmerge:emerge}" v-if="categoryList.length>0" @click="openCart">
      <div :class="{imgCart:cartList.length<1,imgCartActive:cartList.length>0}"></div>
      <div class="divGoodsNum" v-if="cartList.length>0">{{goodsNum}}</div>
      <div class="divPrice">
          <span>￥</span><span>{{totalPrice}}</span>
      </div>
      <div :class="{btnSubmit:cartList.length<1,btnSubmitActive:cartList.length>0}" @click.prevent.stop="toAddOrderPage">去结算</div>
    </div>
    <van-popup v-model="cartDialogShow" round position="bottom" class="dialogCart"
               @open="emerge=true" @closed="emerge=false">
      <div class="divCartTitle">
        <div class="title">已选商品</div>
        <div class="clear" @click="clearCart">
          <span><van-icon name="delete-o" /></span>清空
        </div>
      </div>
      <div class="divCartContent">
        <div v-for="(item,index) in cartList" :key="index" class="divCartItem">
          <van-image :src="getImage(item.image)">
            <template v-slot:error></template>
          </van-image>
          <div class="divDesc">
            <div class="name">{{item.name}}</div>
            <div class="config">{{item.config}}</div>
            <div class="price">
              <span class="spanMoney">￥</span>{{item.amount}}
            </div>
          </div>
          <div class="divNum">
            <div class="divSubtract">
              <img src="images/subtract.png" alt="" @click="changeNumber(item,-1,index)"/>
            </div>
            <div class="divGoodsNum">{{item.number}}</div>
            <div class="divAdd">
              <img src="images/add.png" alt="" @click="changeNumber(item,+1,index)"/>
            </div>
          </div>
          <div class="divSplit"></div>
        </div>
      </div>
    </van-popup>
    <van-dialog v-model="configDialog.show" ref="configDialog" :show-confirm-button="false" class="configDialog">
      <div class="dialogTitle">{{configDialog.name}}</div>
      <div class="divContent">
        <div v-for="(config,index) in configDialog.configs" :key="index">
          <div class="configTitle">{{config.name}}</div>
          <span v-for="item in config.value" :key="item" :class="{spanActive:config.check===item}"
                @click="checkConfigHandle(config,item)">{{item}}</span>
        </div>
      </div>
      <div class="divBottom">
        <div class="price"><span>￥</span>{{configDialog.price}}</div>
        <div v-if="!cartData" class="toCart" @click="addCart(configDialog,false)">加入购物车</div>
        <div v-else class="num">
          <div class="subtract">
            <img src="images/subtract.png" alt="" @click="changeNumber(cartData.cart,-1,cartData.index)"/>
          </div>
          <div class="goodsNum">{{cartData.cart.number}}</div>
          <div class="add">
            <img src="images/add.png" alt="" @click="changeNumber(cartData.cart,+1,cartData.index)"/>
          </div>
        </div>
      </div>
      <div class="divClose" @click="configDialog.show=false">
        <img src="images/close.png"/>
      </div>
    </van-dialog>
    <van-dialog v-model="commodityDialog.show" ref="commodityDialog" :show-confirm-button="false"
                class="commodityDialog" v-if="!configDialog.show">
      <div class="divContainer">
        <van-image :src="getImage(commodityDialog.image)">
          <template v-slot:error></template>
        </van-image>
        <div class="title">{{commodityDialog.name}}</div>
        <div class="content">描述：{{commodityDialog.description}}</div>
      </div>
      <div class="divNum">
        <div class="left">
          <span>￥</span><span>{{commodityDialog.price}}</span>
        </div>
        <div class="right" v-if="commodityDialog.configs">
          <div class="divTypes" v-if="commodityDialog.configs.length>0" @click="openConfigDialog(commodityDialog)">
            选规格
          </div>
          <div class="divAdd" v-else>
            <img src="images/add.png" @click="addCart(commodityDialog,true)"/>
          </div>
        </div>
      </div>
      <div class="detailsDialogClose" @click="commodityDialog.show=false">
        <img src="images/close.png"/>
      </div>
    </van-dialog>
    <van-dialog v-model="comboDialog.show" ref="comboDialog" :show-confirm-button="false"
                class="comboDialog" v-if="!configDialog.show">
      <div class="divContainer">
        <van-image :src="getImage(comboDialog.image)">
          <template v-slot:error></template>
        </van-image>
        <div class="title">{{comboDialog.name}}</div>
        <div class="items">
          <div v-for="(item,index) in comboDialog.commodities" :key="index">
            <div class="subTitle">{{item.commodityName + ' × ' + item.copies}}
              <div class="price">
                <span>￥</span><span>{{item.commodityPrice * item.copies}}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="content">描述：{{comboDialog.description}}</div>
      </div>
      <div class="divNum">
        <div class="left">
          <span>￥</span><span>{{comboDialog.price}}</span>
        </div>
        <div class="right" v-if="comboDialog.configs">
          <div class="divTypes" v-if="comboDialog.configs.length>0" @click="openConfigDialog(comboDialog)">
            选规格
          </div>
          <div class="divAdd" v-else>
            <img src="images/add.png" @click="addCart(comboDialog,true)"/>
          </div>
        </div>
      </div>
      <div class="detailsDialogClose" @click="comboDialog.show = false">
        <img src="images/close.png"/>
      </div>
    </van-dialog>
  </div>
  <!-- 开发环境版本，包含了有帮助的命令行警告 -->
  <script src="plugins/vue/vue.js"></script>
  <!-- 引入组件库 -->
  <script src="plugins/vant/vant.min.js"></script>
  <!-- 引入axios -->
  <script src="plugins/axios/axios.min.js"></script>
  <script src="js/request.js"></script>
  <script src="js/common.js"></script>
  <script src="api/user.js"></script>
  <script src="api/category.js"></script>
  <script src="api/commodity.js"></script>
  <script src="api/combo.js"></script>
  <script src="api/shoppingCart.js"></script>
  <script>
    new Vue({
      el: '#main',
      data() {
        return {
          activeIndex: 0,
          categoryList: [],
          commodityList: [],
          cartList: [],
          emerge: false,
          cartDialogShow: false,
          configDialog: {show: false},
          commodityDialog: {show: false},
          comboDialog: {show: false},
        }
      },
      // computed: 值可以计算缓存，只有相关依赖发生改变时才会重新取值
      computed: {
        // 计算购物车商品数量
        goodsNum() {
          let num = 0
          this.cartList.forEach(item => {
            num += item.number
          })
          return num <= 99 ? num : '99+'
        },
        // 计算购物车总价
        totalPrice() {
          let price = 0
          this.cartList.forEach(item => {
            price += item.amount
          })
          return price
        },
        // 规格框匹配购物车数据
        cartData() {
          let cart = this.cartList.find(cart =>
                  cart.goodsId === this.configDialog.id &&
                  cart.config === this.configDialog.configs.map(config => config.check).join('、'))
          if (cart) {
            let index = this.cartList.indexOf(cart)
            return {cart, index}
          } else {
            return undefined
          }
        },
      },
      created() {
        this.init()
      },
      methods:{
        // 获取初始化数据
        init() {
          // 获取分类数据和商品数据
          getCategoryListApi().then(res => {
            this.categoryList = res.data
            if (this.categoryList.length > 0) {
              let category = this.categoryList[0]
              this.getCommodityList(category.id, category.type)
            }
          }).catch(error => {
            this.$notify({type: 'danger', message: error.message})
          })
          // 判断登录状态，若已登录则获取购物车数据
          isLoginApi().then(res => {
            if (res.data) {
              this.getCartList()
            }
          }).catch(() => {})
        },

        // 获取商品数据
        async getCommodityList(categoryId, type) {
          const params = {categoryId: categoryId, status: 1}
          const res = type === 0 ? await getCommodityListApi(params) : await getComboListApi(params)
          if (res.code === 20000) {
            this.commodityList = res.data
            this.commodityList.forEach(commodity => {
              commodity.configs.forEach(config => {
                config.value = config.value.substring(1, config.value.length - 1).split(',')
              })
            })
          } else {
            this.$notify({type: 'danger', message: res.message})
          }
        },
        // 切换分类
        changeCategory(index, categoryId, type){
          this.activeIndex = index
          this.getCommodityList(categoryId, type)
        },

        // 打开选择规格弹框
        openConfigDialog(item) {
          item.configs.forEach(config => {
            config.check = config.value[0]
          })
          this.configDialog = {...item, show: true}
          this.commodityDialog.show = false
          this.comboDialog.show = false
        },
        // 选中商品某项规格标签
        checkConfigHandle(config,item) {
          config.check = item
          this.configDialog = {...this.configDialog}  // 重新加载对象，使得页面重新渲染
        },

        // 打开商品/套餐详情弹框
        openDetailsDialog(item) {
          if (Array.isArray(item.commodities)) {
            this.comboDialog = {...item, show: true}
          } else {
            this.commodityDialog = {...item, show: true}
          }
        },

        // 获取购物车中的商品数据
        getCartList() {
          getShoppingCartApi().then(res => {
            this.cartList = res.data
          }).catch(error => {
            this.$notify({type: 'danger', message: error.message})
          })
        },
        // 将商品添加到购物车中
        addCart(item, open) {
          const params = {
            goodsId: item.id,
            type: Array.isArray(item.commodities) ? 1 : 0,  // 类型 0:商品,1:套餐
            name: item.name,
            image: item.image,
            config: item.configs.map(config => config.check).join('、'),
            amount:item.price
          }
          addShoppingCartApi(params).then(res => {
            this.getCartList()
            if (open) {
              this.cartDialogShow = true
              this.commodityDialog.show = false
              this.comboDialog.show = false
            }
          }).catch(error => {
            this.$toast(error.message)
          })
        },
        // 弹出购物车
        openCart() {
          if(this.cartList.length > 0) {
            this.cartDialogShow = !this.cartDialogShow;
          }
        },
        // 清空购物车
        clearCart() {
          clearShoppingCartApi().then(res => {
            this.cartList = []
            this.cartDialogShow = false
          }).catch(error => {
            this.$toast(error.message)
          })
        },
        // 改变购物车中商品的数量
        changeNumber(goods, range, index) {
          const number = goods.number + range
          const params = {...goods, number}
          editShoppingCartApi(params).then(res => {
            if (number < 1) {
              // 删除这条商品
              this.cartList.splice(index, 1)
              if (this.cartList.length < 1) {
                this.cartDialogShow = false
              }
            } else {
              // 更改金额和数量
              goods.amount = goods.amount / goods.number * number
              goods.number = number
              this.cartList.splice(index, 1, goods)
            }
          }).catch(error => {
            this.$toast(error.message)
          })
        },

        // 获取图片文件
        getImage(image) {
          return getFileUrl(image, null, '')
        },

        toUserPage() {
          // requestAnimationFrame：可以让移动端页面跳转更流畅
          window.requestAnimationFrame(() => {
            window.location.href = '/front/page/user.html'
          })
        },
        toAddOrderPage() {
          if (this.cartList.length > 0) {
            window.requestAnimationFrame(() => {
              window.location.href = '/front/page/add-order.html'
            })
          }
        }
      }
    })
  </script>
</body>
</html>
